package com.fduss.sota.service.impl;

import com.fduss.sota.dao.RiskCheckTemplateDao;
import com.fduss.sota.domain.RiskCheckTemplate;
import com.fduss.sota.service.RiskCheckTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

/**
 * @Author duocai
 * @Date 2017/6/18
 * @Time 21:48
 */
@Service
@Transactional
public class RiskCheckTemplateServiceImpl implements RiskCheckTemplateService {

    @Autowired
    private RiskCheckTemplateDao riskCheckTemplateDao;

    @Override
    public boolean add(RiskCheckTemplate riskCheckTemplate) {
        checkRiskCheckTemplate(riskCheckTemplate);
        return riskCheckTemplateDao.save(riskCheckTemplate) != null;
    }

    @Override
    public boolean add(List<RiskCheckTemplate> riskCheckTemplates) {
        return riskCheckTemplateDao.save(riskCheckTemplates) != null;
    }

    @Override
    public void delete(RiskCheckTemplate riskCheckTemplate) {
        riskCheckTemplateDao.delete(riskCheckTemplate);
    }

    @Override
    public void deleteAll() {
        riskCheckTemplateDao.deleteAll();
    }

    @Override
    public boolean update(RiskCheckTemplate riskCheckTemplate) {
        checkRiskCheckTemplate(riskCheckTemplate);
        if (riskCheckTemplateDao.findOne(riskCheckTemplate.getId()) == null)
            return false;
        return riskCheckTemplateDao.save(riskCheckTemplate) != null;
    }

    @Override
    public List<RiskCheckTemplate> getAll() {
        return riskCheckTemplateDao.findAll();
    }

    @Override
    public Page<RiskCheckTemplate> getPage(int pageOffset, int pageSize) {
        Pageable page = new PageRequest(pageOffset, pageSize);
        return riskCheckTemplateDao.findAll(page);
    }

    @Override
    public List<RiskCheckTemplate> getByName(String name) {
        return riskCheckTemplateDao.getRiskCheckTemplatesByName(name);
    }

    @Override
    public List<RiskCheckTemplate> search(String key) {
        return riskCheckTemplateDao.getRiskCheckTemplatesByNameContainingOrDescriptionContaining(key, key);
    }

    private void checkRiskCheckTemplate(RiskCheckTemplate riskCheckTemplate) {
        Assert.notNull(riskCheckTemplate.getName(), "the name should not be null");
        Assert.notNull(riskCheckTemplate.getDescription(), "the description should not be null");
        Assert.notNull(riskCheckTemplate.getRiskCheckTemplateItems(), "the items should not be null");
        Assert.notEmpty(riskCheckTemplate.getRiskCheckTemplateItems(), "the items should not be empty");
    }
}
